//
//  LoginAreaCodeView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/6.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import UIKit
import Reusable
import Localize_Swift

extension LoginAreaCodeView: NibLoadable {}

class LoginAreaCodeView: UIView {
    
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var cancelButton: UIButton!
    @IBOutlet weak var tableView: UITableView!
    
    var didSelectedBlock: ((AreaCodeModel) -> Void)?
    var cancelBlock: (() -> Void)?
    
    var list: [AreaCodeModel] = [] {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        initUI()
        
        /// 监听语言的变化
        NotificationCenter.default.addObserver(self, selector: #selector(updateLanguageAction), name: NSNotification.Name(LCLLanguageChangeNotification), object: nil)
        updateLanguageAction()
    }

    
    @IBAction func cancelAction(_ sender: Any) {
        cancelBlock?()
    }
    
    
    // 更新语言
    @objc private func updateLanguageAction() {
        
        titleLabel.text = "选择国家".localized(.login)
        cancelButton.setTitle("取消".localized(.login), for: .normal)
    }
    
}

private extension LoginAreaCodeView {
    
    private func initUI() {
        size = CGSize(width: xScreenW, height: xScreenH*0.5)
        addRoundedCorners(radius: 16)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.rowHeight = 36
        tableView.register(cellType: LoginAreaCodeCell.self)
    }
}

extension LoginAreaCodeView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(for: indexPath, cellType: LoginAreaCodeCell.self)
        cell.model = list[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = list[indexPath.row]
        didSelectedBlock?(model)
    }
    
}
